package plantshop.server;
import java.io.IOException;
import java.io.Serializable;

import plantshop.model.Client;
import plantshop.model.Opponent;


public class ClientCommunicateThread extends Thread implements Serializable{
	private static final long serialVersionUID = 6161888923506398933L;
	private Client client;
	private boolean gameRunning;

	public ClientCommunicateThread(Client client) {
		this.client = client;
		gameRunning = true;
	}

	@Override
	public void run() {
		boolean startGame = false, waitForGame = false, opponentsInitialized = false;
		String name, string="";
		boolean gender;

		while(gameRunning){
			try{
				if(!startGame && !waitForGame){
					client.write(client.getGender());
					client.write(client.getName());
					waitForGame = true;
				} else{
					while(client.hasNext()){
						string = client.read();
						if(string.contains("Begin Game")){
							break;
						}
						gender = Boolean.parseBoolean(string);
						name = client.read();
						client.addOpponent(gender, name);
						opponentsInitialized = true;
					}
					if(opponentsInitialized && !startGame && string.contains("Begin Game")){
						startGame = true;
						client.startGame();
					}
				}
				
				//Works up to here
				//Add functionality for sending data back and forth during game
				if(startGame){
					client.write(client.getPlayerScore());
					client.write(client.getPlayerMoney());
					
					for(Opponent o: client.getOpponents()){
						o.setRating(Integer.parseInt(client.read()));
						o.setMoney(Integer.parseInt(client.read()));
					}
					client.updateTotal();
				}
			}
			catch(IOException e){

			}
		}
	}

	public void endGame(){
		gameRunning = false;
	}
}
